#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    //创建ui界面
    ui->setupUi(this);

    //状态栏初始化创建
    labItemIndex = new QLabel("当前单元格坐标：", this);
    labItemIndex->setMinimumWidth(250);
    labItemType= new QLabel("当前单元格类型：", this);
    labItemType->setMinimumWidth(200);
    ui->statusBar->addWidget(labItemIndex);
    ui->statusBar->addWidget(labItemType);

    //设置保存标志初始值
    save_flag = true;
    //创建空表格
    new_table();

    //关联新建空表格功能
    connect(ui->action_new, &QAction::triggered, this, &MainWindow::new_table);

    //关联文件打开功能
    connect(ui->action_open, &QAction::triggered, this, &MainWindow::open_file);

    //关联文件保存功能
    connect(ui->action_save, &QAction::triggered, this, &MainWindow::save_file);

    //关联文件另存为功能
    connect(ui->action_copy, &QAction::triggered, this, &MainWindow::copy_file);

    //关联数据查找功能
    connect(ui->action_find, &QAction::triggered, this, &MainWindow::search_dialog);

    //关联数据替换功能
    connect(ui->action_replace, &QAction::triggered, this, &MainWindow::replace_dialog);

    //关联数据求和功能
    connect(ui->action_sum, &QAction::triggered, this, &MainWindow::sum_data);

    //关联数据求平均功能
    connect(ui->action_aver, &QAction::triggered, this, &MainWindow::aver_data);

    //关联合并单元格功能
    connect(ui->action_merge, &QAction::triggered, this, &MainWindow::merge_item);

    //关联拆分单元格功能
    connect(ui->action_split, &QAction::triggered, this, &MainWindow::split_item);

    //单元格数据改变
    connect(ui->tableWidget, SIGNAL(cellChanged(int,int)), this, SLOT(item_input(int,int)));

    //当前选择单元格改变
    connect(ui->tableWidget, SIGNAL(currentCellChanged(int,int,int,int)), this, SLOT(item_changed(int,int)));

    //对合并拆分影响太大，搁置
    /*
    //关联删除当前行功能
    connect(ui->action_remove_row, &QAction::triggered, this, &MainWindow::remove_row);

    //关联删除当前列功能
    connect(ui->action_remove_column, &QAction::triggered, this, &MainWindow::remove_column);
    */

    //关联隐藏当前行功能
    connect(ui->action_hide_row, &QAction::triggered, this, &MainWindow::hide_row);

    //关联隐藏当前列功能
    connect(ui->action_hide_column, &QAction::triggered, this, &MainWindow::hide_column);

    //关联显示隐藏行功能
    connect(ui->action_show_row, &QAction::triggered, this, &MainWindow::show_row);

    //关联显示隐藏列功能
    connect(ui->action_show_column, &QAction::triggered, this, &MainWindow::show_column);


    //关联单元格color设置功能
    connect(ui->action_forecolor, &QAction::triggered, this, &MainWindow::edit_forecolor);


    //关联文件排序功能
    connect(ui->action_upsort, &QAction::triggered, this, &MainWindow::upsort_data);
    connect(ui->action_downsort, &QAction::triggered, this, &MainWindow::downsort_data);

    //关联文件筛选功能
    connect(ui->action_equal, &QAction::triggered, this, &MainWindow::select_equal);
    connect(ui->action_nonequal, &QAction::triggered, this, &MainWindow::select_nonequal);
    connect(ui->action_upequal, &QAction::triggered, this, &MainWindow::select_upequal);
    connect(ui->action_downequal, &QAction::triggered, this, &MainWindow::select_downequal);
    connect(ui->action_between, &QAction::triggered, this, &MainWindow::dialog_between);
    connect(ui->action_upaver, &QAction::triggered, this, &MainWindow::select_upaver);
    connect(ui->action_downaver, &QAction::triggered, this, &MainWindow::select_downaver);
    connect(ui->action_eliminate, &QAction::triggered, this, &MainWindow::eliminate);
}

bool MainWindow::check_save()
{
    if(save_flag)
    {
        ui->tableWidget->clear();
        return true;
    }
    int button_index = QMessageBox::warning(this, "提示", "是否保存对文件的更改？",
                                            "保存", "不保存", "取消", 0, 2);
    switch(button_index)
    {
        case 0:
            if(save_file())
            {
                ui->tableWidget->clear();
                return true;
            }
        break;

        case 1:
        {
            ui->tableWidget->clear();
            save_flag = true;
            return true;
        }
    }
    return false;
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if(check_save())
    {
        event->accept();
    }
    else
    {
        event->ignore();
    }
}

void MainWindow::new_table()
{
    if(!check_save())
    {
        return;
    }

    ui->tableWidget->clearSpans();
    ui->tableWidget->setRowCount(100);
    ui->tableWidget->setColumnCount(100);
    for(int i = 0; i < ui->tableWidget->rowCount(); i++)
    {
        for(int j = 0; j < ui->tableWidget->columnCount(); j++)
        {
            QTableWidgetItem *item = new QTableWidgetItem();
            item->setData(Qt::UserRole, ItemType::General);
            ui->tableWidget->setItem(i, j, item);
        }
    }
    filename = "";
    merge_list.clear();
    save_flag = true;
}

void MainWindow::open_file()
{
    if(!check_save())
    {
        return;
    }
    new_table();

    QString FilePath = QCoreApplication::applicationDirPath();
    QString FileName = QFileDialog::getOpenFileName(this, "打开文件", FilePath, "文本文件(*.txt);;流数据文件(*.stm)");

    if(FileName.isEmpty())  //判断是否选择打开文件
    {
        return;
    }

    if(FileName.endsWith(".txt"))
    {
        open_txt_file(FileName);
    }
    else if(FileName.endsWith(".stm"))
    {
        open_stm_file(FileName);
    }
    save_flag = true;
}

void MainWindow::open_txt_file(const QString &FileName)
{
    QFile openFile(FileName);             //打开文件

    if(!openFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QMessageBox::warning(this, "警告", "文件打开失败！", "确定");
        return;
    }

    filename = FileName;                  //记录打开文件
    QTextStream fStream(&openFile);       //用于读取文件内容
    for(int i = 0; !fStream.atEnd() && (i < ui->tableWidget->rowCount()); i++)
    {
        QStringList tmpList = fStream.readLine().split(QRegExp("\\s+"), QString::SkipEmptyParts);
        //这里表明文件单元格内不能有空格，否则会读取错误
        for(int j = 0; j < tmpList.size() && j < ui->tableWidget->columnCount(); j++)
        {
            ui->tableWidget->item(i, j)->setText(tmpList.at(j));
        }
    }
    merge_list.clear();

    openFile.close();                     // 关闭文件
}

void MainWindow::open_stm_file(const QString &FileName)
{
    QFile openFile(FileName);             //打开文件
    if(!openFile.open(QIODevice::ReadOnly))
    {
        QMessageBox::warning(this, "警告", "文件打开失败！", "确定");
        return;
    }

    filename = FileName;                  //记录打开文件
    QDataStream fStream(&openFile);       //用于读取文件内容
    fStream.setVersion(QDataStream::Qt_5_9); //设置版本号，写入和读取的版本号要兼容

    int rowCount, columnCount;
    fStream >> rowCount >> columnCount;
    for(int i = 0; i < rowCount; i++)
    {
        for(int j = 0; j < columnCount; j++)
        {
            int type;
            fStream >> type;
            ui->tableWidget->item(i, j)->setData(Qt::UserRole, type);
            if(type == ItemType::Number)
            {
                double val;
                fStream >> val;
                ui->tableWidget->item(i, j)->setData(Qt::DisplayRole, val);
            }
            else
            {
                QString text;
                fStream >> text;
                ui->tableWidget->item(i, j)->setText(text);
            }
        }
    }
    fStream >> merge_list;
    for(QList<Node>::iterator it = merge_list.begin();
        it != merge_list.end(); it++)
    {
        ui->tableWidget->setSpan(it->get_start_Row(), it->get_start_Column(), it->get_total_Row(), it->get_total_Column());
    }

    openFile.close();                     // 关闭文件
}

bool MainWindow::copy_file()
{
    QString FileName = QFileDialog::getSaveFileName(this, "文件另存为", filename, "文本文件(*.txt);;流数据文件(*.stm)");
    if(FileName.isEmpty())
    {
        return false;
    }

    bool ok = false;
    if(FileName.endsWith(".txt"))
    {
        ok = save_txt_file(FileName);
    }
    else if(FileName.endsWith(".stm"))
    {
        ok = save_stm_file(FileName);
    }

    if(!ok)
    {
        QMessageBox::warning(this, "警告", "文件另存失败！", "确定");
    }
    else
    {
        save_flag = true;
    }
    return ok;
}

bool MainWindow::save_file()
{
    if(filename.isEmpty())
    {
        return copy_file();
    }

    bool ok = false;
    if(filename.endsWith(".txt"))
    {
        ok = save_txt_file(filename);
    }
    else if(filename.endsWith(".stm"))
    {
        ok = save_stm_file(filename);
    }

    if(!ok)
    {
        QMessageBox::warning(this, "警告", "文件保存失败！", "确定");
    }
    else
    {
        save_flag = true;
    }
    return ok;
}

bool MainWindow::save_txt_file(const QString &FileName)
{
    QFile myfile(FileName); //创建一个输出文件的文档
    if (!myfile.open(QIODevice::WriteOnly | QIODevice::Text)) //WriteOnly是往文本中写入的时候用
    {
        QMessageBox::warning(this, "警告", "文件保存失败！", "确定");
        return false;
    }

    QTextStream in(&myfile);
    //获取表格内容
    for(int i = 0; i<ui->tableWidget->rowCount(); i++)
    {
        for (int j = 0; j<ui->tableWidget->columnCount(); j++)
        {
            //QString str =ui->tableWidget->item(i, j)->data(Qt::DisplayRole).toString();
            QString str = ui->tableWidget->item(i, j)->text();
            in << str + "\t";
        }
        in << "\n";
    }

    myfile.close();
    return true;
}

bool MainWindow::save_stm_file(const QString &FileName)
{
    QFile file(FileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate))//WriteOnly是往文本中写入的时候用
    {
        return false;
    }
    QDataStream in(&file);
    in.setVersion(QDataStream::Qt_5_9); //设置版本号，写入和读取的版本号要兼容

    in << ui->tableWidget->rowCount() << ui->tableWidget->columnCount();
    //获取表格内容
    for(int i = 0; i<ui->tableWidget->rowCount(); i++)
    {
        for (int j = 0; j<ui->tableWidget->columnCount(); j++)
        {
            int type = ui->tableWidget->item(i, j)->data(Qt::UserRole).toInt();
            in << type;
            if(type == ItemType::Number)
            {
                in << ui->tableWidget->item(i, j)->data(Qt::DisplayRole).toDouble();
            }
            else
            {
                in << ui->tableWidget->item(i, j)->text();
            }
        }
    }
    in << merge_list;

    file.close();
    return true;
}

void MainWindow::item_input(int row, int column)
{
    QTableWidgetItem *item = ui->tableWidget->item(row, column);
    if(item == Q_NULLPTR)
    {
        return;
    }
    QString str = item->text();
    int oldtype = item->data(Qt::UserRole).toInt();
    ItemType newtype = check_type(str);
    if(oldtype == ItemType::General)
    {
        item->setData(Qt::UserRole, newtype);
        if(newtype == ItemType::Number)
            item->setData(Qt::DisplayRole, str.toDouble());
        //单元格数据改变，导致递归调用item_input()，但不会死循环，
        //这是因为第二次调用没有改变单元格数据
    }
    save_flag = false;
}

MainWindow::ItemType MainWindow::check_type(const QString &str)
{
    if(str.isEmpty())
    {
        return ItemType::General;
    }

    bool ok;
    str.toDouble(&ok);
    if(ok == true)
    {
        return ItemType::Number;
    }
    return ItemType::String;
}

void MainWindow::item_changed(int currentRow, int currentColumn)
{
    QTableWidgetItem* item = ui->tableWidget->item(currentRow, currentColumn);
    if(item == Q_NULLPTR)
    {
        //可通过这个判断某个单元格是否为空，非空时显示坐标
        return;
    }
    int type = item->data(Qt::UserRole).toInt();
    labItemIndex->setText(QString::asprintf("当前单元格坐标：%d 行，%d 列", currentRow + 1, currentColumn + 1));
    labItemType->setText("当前单元格类型：" + type_name[type]);
}

void MainWindow::search_dialog()
{
    //创建查找对话框
    MyFindDialog *find_dialog;
    QTableWidgetItem *currentItem = ui->tableWidget->currentItem();
    if(currentItem != Q_NULLPTR)
    {
        QString text = currentItem->text();
        find_dialog = new MyFindDialog(text, this);
    }
    else
    {
        find_dialog = new MyFindDialog(this);
    }

    //设置对话框关闭后自动delete释放内存
    find_dialog->setAttribute(Qt::WA_DeleteOnClose);

    //链接对话框信号与查找槽函数
    connect(find_dialog, SIGNAL(find_next_clicked(QString)), this, SLOT(search_next(QString)));
    connect(find_dialog, SIGNAL(find_all_clicked(QString)), this, SLOT(search_all(QString)));

    //非模态显示对话框
    find_dialog->show();
}

void MainWindow::search_next(const QString &text)
{
    int i, start_row;
    int j, start_column;
    bool find_flag = false;

    if((ui->tableWidget->rowCount() == 0) && (ui->tableWidget->columnCount() == 0))
    {
        QMessageBox::warning(this, "警告", "无法找到要查找的内容。");
        return;
    }

    i = start_row = ui->tableWidget->currentRow();
    j = start_column = ui->tableWidget->currentColumn();
    do
    {
        j++;
        if(j >= ui->tableWidget->columnCount())
        {
            j = 0;
            i++;
            if(i >= ui->tableWidget->rowCount())
            {
                i = 0;
            }
        }
        if (text == ui->tableWidget->item(i, j)->text())
        {
            ui->tableWidget->setCurrentCell(i, j);
            find_flag = true;
            break;
        }
    } while((i != start_row) || (j != start_column));
    if(find_flag == false)
    {
        QMessageBox::warning(this, "警告", "无法找到要查找的内容。");
    }
}

void MainWindow::search_all(const QString &text)
{
    ui->tableWidget->clearSelection();
    QList<QTableWidgetItem *> list = ui->tableWidget->findItems(text, Qt::MatchExactly);
    if(list.isEmpty())
    {
        QMessageBox::warning(this, "警告", "无法找到要查找的内容。");
        return;
    }

    for (QList<QTableWidgetItem *>::iterator it = list.begin();
         it != list.end(); it++)
    {
        (*it)->setSelected(true);
    }
}

void MainWindow::replace_dialog()
{
    //创建查找对话框
    MyReplaceDialog *replace_dialog;
    QTableWidgetItem *currentItem = ui->tableWidget->currentItem();
    if(currentItem != Q_NULLPTR)
    {
        QString text = currentItem->text();
        replace_dialog = new MyReplaceDialog(text, this);
    }
    else
    {
        replace_dialog = new MyReplaceDialog(this);
    }

    //设置对话框关闭后自动delete释放内存
    replace_dialog->setAttribute(Qt::WA_DeleteOnClose);

    //链接对话框信号与查找槽函数
    connect(replace_dialog, SIGNAL(replace_next_clicked(QString, QString)), this, SLOT(replace_next(QString, QString)));
    connect(replace_dialog, SIGNAL(replace_all_clicked(QString, QString)), this, SLOT(replace_all(QString, QString)));
    connect(replace_dialog, SIGNAL(skip_clicked(QString)), this, SLOT(search_next(QString)));

    //非模态显示对话框
    replace_dialog->show();
}

void MainWindow::replace_next(const QString &find_text, const QString &replace_text)
{
    int i, start_row;
    int j, start_column;
    bool find_flag = false;

    if((ui->tableWidget->rowCount() == 0) && (ui->tableWidget->columnCount() == 0))
    {
        QMessageBox::warning(this, "警告", "无法找到要查找的内容。");
        return;
    }

    i = start_row = ui->tableWidget->currentRow();
    j = start_column = ui->tableWidget->currentColumn();
    do
    {
        j++;
        if(j >= ui->tableWidget->columnCount())
        {
            j = 0;
            i++;
            if(i >= ui->tableWidget->rowCount())
            {
                i = 0;
            }
        }
        if (find_text == ui->tableWidget->item(i, j)->text())
        {
            ui->tableWidget->setCurrentCell(i, j);
            ui->tableWidget->item(i, j)->setText(replace_text);
            find_flag = true;
            break;
        }
    } while((i != start_row) || (j != start_column));
    if(find_flag == false)
    {
        QMessageBox::warning(this, "警告", "无法找到要查找的内容。");
    }
}

void MainWindow::replace_all(const QString &find_text, const QString &replace_text)
{
    QList<QTableWidgetItem *> list = ui->tableWidget->findItems(find_text, Qt::MatchExactly);
    if(list.isEmpty())
    {
        QMessageBox::warning(this, "警告", "无法找到要查找的内容。");
        return;
    }

    ui->tableWidget->clearSelection();
    for (QList<QTableWidgetItem *>::iterator it = list.begin();
         it != list.end(); it++)
    {
        (*it)->setText(replace_text);
    }
}

void MainWindow::sum_data()
{
    //支持double型的求和，即单元格内容要符合double型的表达形式，如123.45
    //如果含有非数学运算符的字符，则默认单元格转化的值为0
    QList<QTableWidgetItem *> list = ui->tableWidget->selectedItems();
    double sum = 0;
    for (QList<QTableWidgetItem *>::iterator it = list.begin();
         it != list.end(); it++)
    {
        sum += (*it)->text().toDouble();
    }

    //弹窗输出结果
    QMessageBox::information(this, "结果", QString("它们的和是%1。").arg(sum), "确定");
}

void MainWindow::aver_data()
{
    //支持对double型的数据处理

    QList<QTableWidgetItem *> list = ui->tableWidget->selectedItems();
    if(list.isEmpty())
    {
        QMessageBox::warning(this, "警告", "请先选中单元格。", "确定");
        return;
    }
    double aver = 0, count = 0;
    bool ok;
    for (QList<QTableWidgetItem *>::iterator it = list.begin();
         it != list.end(); it++)
    {
        aver += (*it)->text().toDouble(&ok);
        if(ok)
        {
            count++;
        }
    }
    if(count == 0)
    {
        QMessageBox::warning(this, "警告", "请选中可求平均的单元格。", "确定");
        return;
    }
    aver /= count;

    //弹窗输出结果
    QMessageBox::information(this, "结果", QString("它们的平均值是%1。").arg(aver), "确定");
}

void MainWindow::merge_item()
{
    QList<QTableWidgetSelectionRange> list = ui->tableWidget->selectedRanges();

    //判断是否选中了单元格
    if(list.size() == 0)
    {
        QMessageBox::warning(this, "警告", "请先选中单元格。", "确定");
        return;
    }

    //弹窗提示单元格将被覆盖
    int button_index = QMessageBox::information(this, "提示", "除了左上角以外的单元格将被覆盖。",
                                                "确定", "取消", "", 0, 1);
    if(button_index == 1)
    {
        //点击取消或按ESC键时，取消合并
        return;
    }

    //起始行号和列号
    int start_row = list.first().topRow(), start_column = list.first().leftColumn();
    //结束行号和列号
    int end_row = list.first().bottomRow(), end_column = list.first().rightColumn();
    //合并的总行数和列数
    int total_row, total_column;

    for(QList<QTableWidgetSelectionRange>::iterator it = list.begin();
        it != list.end(); it++)
    {
        //先把每个单元格还原成1x1
        ui->tableWidget->setSpan(it->topRow(), it->leftColumn(), 1, 1);

        //从合并列表中删除还原的单元格
        merge_list.removeOne(Node(it->topRow(), it->leftColumn()));

        if(it->topRow() <= start_row && it->leftColumn() <= start_column)
        {
            start_row = it->topRow();
            start_column = it->leftColumn();
        }
        if(it->bottomRow() >= end_row && it->rightColumn() >= end_column)
        {
            end_row = it->bottomRow();
            end_column = it->rightColumn();
        }
    }
    total_row = end_row + 1 - start_row;
    total_column = end_column + 1 - start_column;

    //合并选中单元格
    ui->tableWidget->setSpan(start_row, start_column, total_row, total_column);

    //覆盖掉合并的单元格的内容
    QString text = ui->tableWidget->item(start_row, start_column)->text();
    for(int i = start_row; i <= end_row; i++)
    {
        for(int j = start_column; j <= end_column; j++)
        {
            ui->tableWidget->item(i,j)->setText("");
        }
    }
    ui->tableWidget->item(start_row, start_column)->setText(text);

    //将代表合并单元格的节点添加到合并列表中
    merge_list.append(Node(start_row, start_column, total_row, total_column));

    //Node *_c = new Node(start_row, start_column, totel_row, totel_column);
    //node->insert_Node(_c);
    //qDebug() << ui->tableWidget->item(top, left)->flags()
    //        << (ui->tableWidget->item(top, left) == ui->tableWidget->item(top + 1, left + 1));
}

void MainWindow::split_item()
{
    //获取选中的要拆分的单元格
    QList<QTableWidgetItem *> list = ui->tableWidget->selectedItems();

    //判断是否选中了单元格
    if(list.size() == 0)
    {
        QMessageBox::warning(this, "警告", "请先选中单元格。", "确定");
        return;
    }

    for (QList<QTableWidgetItem *>::iterator it = list.begin();
         it != list.end(); it++)
    {
        //将单元格还原成1x1
        ui->tableWidget->setSpan((*it)->row(), (*it)->column(), 1, 1);

        //从合并列表中删除拆分的单元格
        merge_list.removeOne(Node((*it)->row(), (*it)->column()));
    }
}

void MainWindow::upsort_data()
{
    if(!merge_list.isEmpty())
    {
        QMessageBox::warning(this, "警告", "表格含有合并单元格，无法排序", "确定");
        return;
    }
    int curcolumn = ui->tableWidget->currentColumn();
    ui->tableWidget->sortItems(curcolumn,Qt::AscendingOrder);
}

void MainWindow::downsort_data()
{
    if(!merge_list.isEmpty())
    {
        QMessageBox::warning(this, "警告", "表格含有合并单元格，无法排序", "确定");
        return;
    }
    int curcolumn = ui->tableWidget->currentColumn();
    ui->tableWidget->sortItems(curcolumn,Qt::DescendingOrder);
}

void MainWindow::select_equal()
{
    QString dlgTitle1="筛选数据对话框";
    QString txtLabel1="保留等于所输入数字的数据";
    QString defaultInput1="NULL";

    QLineEdit::EchoMode echoMode1=QLineEdit::Normal;//正常文字输入
    //QLineEdit::EchoMode echoMode=QLineEdit::Password;//密码输入

    QString text1 = QInputDialog::getText(this, dlgTitle1, txtLabel1, echoMode1, defaultInput1);

    int curcolumn = ui->tableWidget->currentColumn();
    for (int i = 0; i<ui->tableWidget->rowCount(); i++)
    {
        QString str = ui->tableWidget->item(i, curcolumn)->text();
        if (str != text1)
        {
            ui->tableWidget->hideRow(i);
        }
    }
}

void MainWindow::select_nonequal()
{
    QString dlgTitle1="筛选数据对话框";
    QString txtLabel1="保留不等于所输入数字的数据";
    QString defaultInput1="NULL";

    QLineEdit::EchoMode echoMode1=QLineEdit::Normal;//正常文字输入
    //QLineEdit::EchoMode echoMode=QLineEdit::Password;//密码输入

    QString text1 = QInputDialog::getText(this, dlgTitle1, txtLabel1, echoMode1, defaultInput1);
    int curcolumn = ui->tableWidget->currentColumn();
    for (int i = 0; i<ui->tableWidget->rowCount(); i++)
    {
        QString str = ui->tableWidget->item(i, curcolumn)->text();
        if (str == text1)
        {
            ui->tableWidget->hideRow(i);
        }
    }
}

void MainWindow::select_upequal()
{
    QString dlgTitle1="筛选数据对话框";
    QString txtLabel1="保留大于等于所输入数字的数据";
    QString defaultInput1="NULL";

    QLineEdit::EchoMode echoMode1=QLineEdit::Normal;//正常文字输入
    //QLineEdit::EchoMode echoMode=QLineEdit::Password;//密码输入

    QString text1 = QInputDialog::getText(this, dlgTitle1, txtLabel1, echoMode1, defaultInput1);
    int curcolumn = ui->tableWidget->currentColumn();
    for (int i = 0; i<ui->tableWidget->rowCount(); i++)
    {
        QString str = ui->tableWidget->item(i, curcolumn)->text();
        if (str.toDouble() < text1.toDouble())
        {
            ui->tableWidget->hideRow(i);
        }
    }
}

void MainWindow::select_downequal()
{
    QString dlgTitle1="筛选数据对话框";
    QString txtLabel1="保留小于等于所输入数字的数据";
    QString defaultInput1="NULL";

    QLineEdit::EchoMode echoMode1=QLineEdit::Normal;//正常文字输入
    //QLineEdit::EchoMode echoMode=QLineEdit::Password;//密码输入

    QString text1 = QInputDialog::getText(this, dlgTitle1, txtLabel1, echoMode1, defaultInput1);
    int curcolumn = ui->tableWidget->currentColumn();
    for (int i = 0; i<ui->tableWidget->rowCount(); i++)
    {
        QString str = ui->tableWidget->item(i, curcolumn)->text();
        if (str.toDouble() > text1.toDouble())
        {
            ui->tableWidget->hideRow(i);
        }
    }
}

void MainWindow::dialog_between()
{
    MybetweenDialog *between_dialog = new MybetweenDialog(this);

    //设置对话框关闭后自动delete释放内存
    between_dialog->setAttribute(Qt::WA_DeleteOnClose);

    //链接对话框信号与查找槽函数
    connect(between_dialog, SIGNAL(ok_clicked(double,double)), this, SLOT(select_between(double,double)));

    //非模态显示对话框
    between_dialog->show();
}

void MainWindow::select_between(double min, double max)
{
    int curcolumn = ui->tableWidget->currentColumn();
    double val = 0;
    for (int i = 0; i<ui->tableWidget->rowCount(); i++)
    {
        QString str = ui->tableWidget->item(i, curcolumn)->text();
        val = str.toDouble();
        if ((val < min)||(val > max))
        {
            ui->tableWidget->hideRow(i);
        }
    }
}

void MainWindow::select_upaver()
{
    int curcolumn = ui->tableWidget->currentColumn();
    int i;
    double sum = 0, aver = 0, val = 0;
    for (i = 0; i<ui->tableWidget->rowCount(); i++)
    {
        QString str1 = ui->tableWidget->item(i, curcolumn)->text();
        val = str1.toDouble();
        sum = sum + val;
    }
    aver = sum / (i-1);
    for (i = 0; i<ui->tableWidget->rowCount(); i++)
    {

        QString str2 = ui->tableWidget->item(i, curcolumn)->text();
        val = str2.toDouble();
        if (val <= aver)
        {
            ui->tableWidget->hideRow(i);
        }
    }
}

void MainWindow::select_downaver()
{
    int curcolumn = ui->tableWidget->currentColumn();
    int i;
    double sum = 0, aver = 0, val = 0;
    for (i = 0; i<ui->tableWidget->rowCount(); i++)
    {
        QString str1 = ui->tableWidget->item(i, curcolumn)->text();
        val = str1.toDouble();
        sum = sum + val;
    }
    aver = sum / (i-1);
    for (i = 0; i<ui->tableWidget->rowCount(); i++)
    {

        QString str2 = ui->tableWidget->item(i, curcolumn)->text();
        val = str2.toDouble();
        if (val >= aver)
        {
            ui->tableWidget->hideRow(i);
        }
    }
}

void MainWindow::eliminate()
{
    for (int i = 0; i<ui->tableWidget->rowCount(); i++)
    {
        ui->tableWidget->showRow(i);
    }
}

//对合并拆分影响太大，搁置
/*
void MainWindow::remove_row()
{
    ui->tableWidget->removeRow(ui->tableWidget->currentRow());
}

void MainWindow::remove_column()
{
    ui->tableWidget->removeColumn(ui->tableWidget->currentColumn());
}
*/

void MainWindow::hide_row()
{
    QList<QTableWidgetSelectionRange> list = ui->tableWidget->selectedRanges();
    for(QList<QTableWidgetSelectionRange>::iterator it = list.begin();
        it != list.end(); it++)
    {
        for(int i = it->topRow(); i <= it->bottomRow(); i++)
        {
            ui->tableWidget->hideRow(i);
        }
    }
}

void MainWindow::hide_column()
{
    QList<QTableWidgetSelectionRange> list = ui->tableWidget->selectedRanges();
    for(QList<QTableWidgetSelectionRange>::iterator it = list.begin();
        it != list.end(); it++)
    {
        for(int j = it->leftColumn(); j <= it->rightColumn(); j++)
        {
            ui->tableWidget->hideColumn(j);
        }
    }
}

void MainWindow::show_row()
{
    QList<QTableWidgetSelectionRange> list = ui->tableWidget->selectedRanges();
    for(QList<QTableWidgetSelectionRange>::iterator it = list.begin();
        it != list.end(); it++)
    {
        for(int i = it->topRow(); i <= it->bottomRow(); i++)
        {
            ui->tableWidget->showRow(i);
        }
    }
}

void MainWindow::show_column()
{
    QList<QTableWidgetSelectionRange> list = ui->tableWidget->selectedRanges();
    for(QList<QTableWidgetSelectionRange>::iterator it = list.begin();
        it != list.end(); it++)
    {
        for(int j = it->leftColumn(); j <= it->rightColumn(); j++)
        {
            ui->tableWidget->showColumn(j);
        }
    }
}

void MainWindow::edit_forecolor()
{
    //创建forecolor设置对话框
    MyForecolorDialog *forecolor_dialog;
    forecolor_dialog = new MyForecolorDialog(this);
    //设置对话框关闭后自动delete释放内存
    forecolor_dialog->setAttribute(Qt::WA_DeleteOnClose);

    //链接对话框信号与设置槽函数
    /*字体颜色*/
    connect(forecolor_dialog, SIGNAL(comboBox_activated(QString)), this,  SLOT(set_forecolor(QString)));
    /*背景颜色*/
    connect(forecolor_dialog, SIGNAL(comboBoxBack_activated(QString)), this,  SLOT(set_backcolor(QString)));
    /*粗体*/
    connect(forecolor_dialog, SIGNAL(checkBoxBold_stateChanged(int)), this, SLOT(set_bold(int)));
    /*斜体*/
    connect(forecolor_dialog, SIGNAL(checkBoxItaly_stateChanged(int)), this, SLOT(set_italy(int)));
    /*字体类型*/
    connect(forecolor_dialog, SIGNAL(comboBoxFonts_activated(QString)), this, SLOT(set_fonts(QString)));
    /*字体大小*/
    connect(forecolor_dialog, SIGNAL(comboBoxSize_activated(QString)), this, SLOT(set_fontsize(QString)));
    /*居左*/
    connect(forecolor_dialog, SIGNAL(font_left_clicked()), this, SLOT(set_fontleft()));
    /*居中*/
    connect(forecolor_dialog, SIGNAL(font_mid_clicked()), this, SLOT(set_fontmid()));
    /*居右*/
    connect(forecolor_dialog, SIGNAL(font_right_clicked()), this, SLOT(set_fontright()));
    /*类型*/
    connect(forecolor_dialog, SIGNAL(comboBoxType_activated(QString)), this, SLOT(set_type(QString)));

    //非模态显示对话框
    forecolor_dialog->show();
}

/*设置单元格的字体颜色*/
void MainWindow::set_forecolor(const QString &text)
{
    QList<QTableWidgetItem *> list = ui->tableWidget->selectedItems();
    /*判断是否选中了单元格*/
    if(list.size() == 0)
    {
        QMessageBox::warning(this, "警告", "请先选中单元格。", "确定");
        return ;
    }

    for (QList<QTableWidgetItem *>::iterator it = list.begin();
         it != list.end(); it++)
    {
        ui->tableWidget->selectedItems();

        if(text == "Red")
            (*it)->setForeground(Qt::red);
        else if(text == "Black")
            (*it)->setForeground(Qt::black);
        else if(text == "Yellow")
            (*it)->setForeground(Qt::yellow);
        else if (text == "Green")
            (*it)->setForeground(Qt::green);
        else if (text == "Gray")
            (*it)->setForeground(Qt::gray);
    }
}

/*设置单元格的背景颜色*/
void MainWindow::set_backcolor(QString text)
{
    QList<QTableWidgetItem *> list = ui->tableWidget->selectedItems();
    /*判断是否选中了单元格*/
    if(list.size() == 0)
    {
        QMessageBox::warning(this, "警告", "请先选中单元格。", "确定");
        return ;
    }

    for (QList<QTableWidgetItem *>::iterator it = list.begin();
         it != list.end(); it++)
    {
        ui->tableWidget->selectedItems();

        if(text == "Red")
            (*it)->setBackground(Qt::red);
        else if(text == "Black")
            (*it)->setBackground(Qt::black);
        else if(text == "Yellow")
            (*it)->setBackground(Qt::yellow);
        else if (text == "Green")
            (*it)->setBackground(Qt::green);
        else if (text == "Gray")
            (*it)->setBackground(Qt::gray);
        else if(text == "White")
            (*it)->setBackground(Qt::white);
        else if(text == "Blue")
            (*it)->setBackground(Qt::blue);
    }
}

void MainWindow::set_bold(int arg1)
{
    QList<QTableWidgetItem *> list = ui->tableWidget->selectedItems();
    /*判断是否选中了单元格*/
    if(list.size() == 0)
    {
        QMessageBox::warning(this, "警告", "请先选中单元格。", "确定");
        return ;
    }

    for (QList<QTableWidgetItem *>::iterator it = list.begin();
         it != list.end(); it++)
    {
        QFont nullFont = (*it)->font();
        if(arg1)
            nullFont.setBold(true);
         else
            nullFont.setBold(false);
        (*it)->setFont(nullFont);
    }
}

void MainWindow::set_italy(int arg1)
{
    QList<QTableWidgetItem *> list = ui->tableWidget->selectedItems();
    /*判断是否选中了单元格*/
    if(list.size() == 0)
    {
        QMessageBox::warning(this, "警告", "请先选中单元格。", "确定");
        return ;
    }

    for (QList<QTableWidgetItem *>::iterator it = list.begin();
         it != list.end(); it++)
    {
        QFont nullFont = (*it)->font();
        if(arg1)
            nullFont.setItalic(true);
        else
            nullFont.setItalic(false);

        (*it)->setFont(nullFont);
    }
}

/*设置单元格的字体大小*/
void MainWindow::set_fontsize(const QString &arg1)
{
    QList<QTableWidgetItem *> list = ui->tableWidget->selectedItems();
    /*判断是否选中了单元格*/
    if(list.size() == 0)
    {
        QMessageBox::warning(this, "警告", "请先选中单元格。", "确定");
        return ;
    }

    for (QList<QTableWidgetItem *>::iterator it = list.begin();
         it != list.end(); it++)
    {
        QFont newFont = (*it)->font();
        newFont.setPointSize(arg1.toInt());
        (*it)->setFont(newFont);
    }
}

/*设置字体居左*/
void MainWindow::set_fontleft()
{
    QList<QTableWidgetItem *> list = ui->tableWidget->selectedItems();
    /*判断是否选中了单元格*/
    if(list.size() == 0)
    {
        QMessageBox::warning(this, "警告", "请先选中单元格。", "确定");
        return ;
    }

    for (QList<QTableWidgetItem *>::iterator it = list.begin();
         it != list.end(); it++)
    {
        (*it)->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    }
}

/*设置字体居中*/
void MainWindow::set_fontmid()
{
    QList<QTableWidgetItem *> list = ui->tableWidget->selectedItems();
    /*判断是否选中了单元格*/
    if(list.size() == 0)
    {
        QMessageBox::warning(this, "警告", "请先选中单元格。", "确定");
        return ;
    }

    for (QList<QTableWidgetItem *>::iterator it = list.begin();
         it != list.end(); it++)
    {
        (*it)->setTextAlignment(Qt::AlignCenter);
    }
}

/*设置字体居右*/
void MainWindow::set_fontright()
{
    QList<QTableWidgetItem *> list = ui->tableWidget->selectedItems();
    /*判断是否选中了单元格*/
    if(list.size() == 0)
    {
        QMessageBox::warning(this, "警告", "请先选中单元格。", "确定");
        return ;
    }

    for (QList<QTableWidgetItem *>::iterator it = list.begin();
         it != list.end(); it++)
    {
        (*it)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
    }
}

/*设置单元格中的字体*/
void MainWindow::set_fonts(const QString &arg1)
{
    QList<QTableWidgetItem *> list = ui->tableWidget->selectedItems();
    /*判断是否选中了单元格*/
    if(list.size() == 0)
    {
        QMessageBox::warning(this, "警告", "请先选中单元格。", "确定");
        return ;
    }

    for (QList<QTableWidgetItem *>::iterator it = list.begin();
         it != list.end(); it++)
    {
        QFont newFont = (*it)->font();
        if(arg1 == "Helvetica")  
            newFont.setFamily("Helvetica");
        else if(arg1 == "SimSun")
            newFont.setFamily("SimSun");
        else if(arg1 == "SimHei")
            newFont.setFamily("SimHei");
        else if(arg1 == "Microsoft YaHei")
            newFont.setFamily("Microsoft YaHei");
        else if(arg1 =="KaiTi")
            newFont.setFamily("KaiTi");

        (*it)->setFont(newFont);
    }
}

/*设置为选中的类型*/
void MainWindow::set_type(const QString &arg1)
{
    QList<QTableWidgetItem *> list = ui->tableWidget->selectedItems();
    /*判断是否选中了单元格*/
    if(list.size() == 0)
    {
        QMessageBox::warning(this, "警告", "请先选中单元格。", "确定");
        return;
    }

    for (QList<QTableWidgetItem *>::iterator it = list.begin();
         it != list.end(); it++)
    {
        if(arg1 == type_name[ItemType::String])
        {
            (*it)->setData(Qt::UserRole, ItemType::String);
            QString text = (*it)->data(Qt::DisplayRole).toString();
            (*it)->setText(text);
        }
        else if(arg1 == type_name[ItemType::Number])
        {
            (*it)->setData(Qt::UserRole, ItemType::Number);
            QString text = (*it)->text();
            (*it)->setData(Qt::DisplayRole, text.toDouble());
        }
    }
}

MainWindow::~MainWindow()
{
    delete ui;
//    qDebug() << "MainWindow析构函数被调用";
}
